import { defineComponent, ref } from 'vue'
import { store } from '@/store'
import router from '@/router'
import './index.less'
import { useToast } from '@/plugins/toast/api'

export default defineComponent({
	name: 'login',
	setup() {
		const username = ref('')
		const password = ref('')
		const unFocus = ref(false)
		const pwFocus = ref(false)

		const login = async () => {
			if (!username.value.trim()) {
				useToast({
					text: '请输入用户名'
				})
				return
			}
			if (!password.value.trim()) {
				useToast({
					text: '请输入密码'
				})
				return
			}
			const res = await store.dispatch('user/login', {
				username: username.value,
				password: password.value
			})
			if (res) {
				router.push('/')
			}
		}

		const pwEnter = (e: KeyboardEvent) => {
			if (e.code === 'Enter') {
				login()
			}
		}

		return () => (
			<div class="login">
				<div class="login-title">todo</div>
				<div class="login-container">
					<label for="username">
						<div class={{ username: true, focus: unFocus.value }}>
							<span class="label">
								<i class="icon iconfont">&#xe659;</i>
							</span>
							<input
								v-model={username.value}
								id="username"
								type="text"
								placeholder="用户名"
								onFocus={() => (unFocus.value = true)}
								onBlur={() => (unFocus.value = false)}
							/>
						</div>
					</label>
					<label for="password">
						<div class={{ password: true, focus: pwFocus.value }}>
							<span class="label">
								<i class="icon iconfont">&#xe650;</i>
							</span>
							<input
								v-model={password.value}
								id="password"
								type="password"
								placeholder="密码"
								onKeypress={pwEnter}
								onFocus={() => (pwFocus.value = true)}
								onBlur={() => (pwFocus.value = false)}
							/>
						</div>
					</label>
					<div class="login-btn">
						<my-button onClick={login}>登录</my-button>
					</div>
				</div>
			</div>
		)
	}
})
